﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Controller;
using Entity;
using System.Collections;


namespace Web
{
    public partial class EditVendorPO : System.Web.UI.Page
    {
        Helper helper = new Helper();
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                if (Request.QueryString["vendorPOId"] != null)
                {
                    int vendPOId = Convert.ToInt32(Request.QueryString["vendorPOId"]);
                    VendorPOController vendorPoController = new VendorPOController();
                    VendorPOEntity vendorPoEntity = vendorPoController.findVendorPOById(vendPOId);
                    //if (vendorPoEntity.Status != "new")//if the items of this po have been stock in partial or finished, cannot update this po
                    //{
                    //    SubmitButton.Enabled = false;
                    //}
                    //else
                    //{
                        VendorPOItemController vendorPoItemController = new VendorPOItemController();
                        IList<VendorPOItemEntity> vendorPoItemEntities =
                            vendorPoItemController.findVendorPOItemsByVendorPOId(vendPOId);
                        VendorPOItemGridView.DataSource = vendorPoItemEntities;
                        VendorPOItemGridView.DataBind();
                        Session["VendorPOItems"] = vendorPoItemEntities;
                        VendorController vendorController = new VendorController();
                        IList<VendorEntity> vendorEntities = vendorController.FindAllVendorEntities();
                        VendorDropDownList.DataSource = vendorEntities;
                        VendorDropDownList.DataValueField = "Id";
                        VendorDropDownList.DataTextField = "ShortName";
                        VendorDropDownList.DataBind();

                        //Bind the vendor po info.
                        POTypeRadioButtonList.SelectedValue = vendorPoEntity.Type;
                        POTypeRadioButtonList.Enabled = false;
                        CurrentPONolabel.Text = vendorPoEntity.No;
                        VendorPONoTextBox.Text = vendorPoEntity.No;
                        VendorDropDownList.SelectedValue = vendorPoEntity.VendId.ToString();
                    

                        if(vendorPoEntity.Address!=string.Empty)
                        {
                            string[] address = vendorPoEntity.Address.Split(',');
                            if (address.Length==3)
                            {
                                AddressTextBox1.Text = address[0];
                                AddressTextBox2.Text = address[1];
                                AddressTextBox3.Text = address[2];
                            }
                            else if(address.Length == 2)
                            {
                                AddressTextBox1.Text = address[0];
                                AddressTextBox2.Text = address[1];
                                AddressTextBox3.Text = "";
                            }
                            else if(address.Length == 1)
                            {
                                AddressTextBox1.Text = address[0];
                                AddressTextBox2.Text = "";
                                AddressTextBox3.Text = "";
                            }
                            else
                            {
                                AddressTextBox1.Text = "";
                                AddressTextBox2.Text = "";
                                AddressTextBox3.Text = "";
                            }
                        }

                        ZipCodeTextBox.Text = vendorPoEntity.ZipCode;
                        AttentionTextBox.Text = vendorPoEntity.Attention;
                        PhoneTextBox.Text = vendorPoEntity.Phone;
                        FaxTextBox.Text = vendorPoEntity.Fax;
                        CreatedByTextBox.Text = vendorPoEntity.CreatedBy.ToString();
                        ApprovedByTextBox.Text = vendorPoEntity.ApprovedBy.ToString();
                        RefereceTextBox.Text = vendorPoEntity.Reference;
                        RemarkTextBox.Text = vendorPoEntity.Remark;
                        TotalQtyTextBox.Text = vendorPoEntity.TotalQty.ToString();


                        SummaryPOTypeLabel.Text = vendorPoEntity.Type;
                        SummaryTotalOpenQtyLabel.Text = vendorPoEntity.TotalOpenQty.ToString();

                        //Bind the Insert area drop down
                        ProductController productController = new ProductController();
                        IList<ProductEntity> productEntities = productController.FindAllProductEntities();
                        NoAndRevDropDownList.DataSource = productEntities;
                        NoAndRevDropDownList.DataValueField = "Id";
                        NoAndRevDropDownList.DataTextField = "ProductNoAndRevision";
                        NoAndRevDropDownList.DataBind();
                        NoAndRevDropDownList.Items.Insert(0, new ListItem("--Select Product--", "0"));
                        InsertButton.Enabled = false;
                        //Set today to insert requested date textbox calendar
                        InsertRequestedDateTextBox_CalendarExtender.SelectedDate = System.DateTime.Now;

                    //}
                }
                else
                {
                    Response.Redirect("Default.aspx");
                }
            }
            this.PreRender += new EventHandler(UpdateFlashMessage);
        }

        private void UpdateFlashMessage(object sender, EventArgs e)
        {
            helper.ShowFlashMessage(FlashMessageLabel);
        }

        protected void DeleteVendorPOItemButton_Click(object sender, EventArgs e)
        {
            try
            {
                int rowIndex = ((GridViewRow) ((Button) sender).NamingContainer).RowIndex;
                int massage = 0;
                IList<VendorPOItemEntity> vendorPOItemEntities = Session["VendorPOItems"] as IList<VendorPOItemEntity>;
                int vendorPOItemId = vendorPOItemEntities[rowIndex].Id;
                
                
                VendorPOItemController vendorPoItemController=new VendorPOItemController();
                int i=vendorPoItemController.DeleteVendorPOItemByItemId(vendorPOItemId);
                if(i==0)
                {
                    vendorPOItemEntities.RemoveAt(rowIndex);
                    VendorPOItemGridView.DataSource = vendorPOItemEntities;
                    VendorPOItemGridView.DataBind();
                }
                else
                {
                    Session["FlashMessage"] = "Error: " + "This record cannot be deleted!";
                    Session["FlashMessageType"] = "error";
                }
                Session["VendorPOItems"] = vendorPOItemEntities;
            }
            catch(Exception ex)
            {
                Session["FlashMessage"] = "Error: " + ex.Message;
                Session["FlashMessageType"] = "error";
            }
        }

        protected void CloseVendorPOItemButton_Click(object sender, EventArgs e)
        {
            try
            {


                int rowIndex = ((GridViewRow)((Button)sender).NamingContainer).RowIndex;
                int massage = 0;
                IList<VendorPOItemEntity> vendorPOItemEntities = Session["VendorPOItems"] as IList<VendorPOItemEntity>;
                //string oldStatus = CustomerPOItemEntities[rowIndex].Status;
                //Session["OldStatus"] = oldStatus;
                if (Session["CloseOpen"] == null)
                {

                    vendorPOItemEntities[rowIndex].Status = "closed";
                    Session["CloseOpen"] = "Closed";
                    

                }
                else
                {
                    if (Session["CloseOpen"].ToString() == "Closed")
                    {
                        if (vendorPOItemEntities[rowIndex].CompleteQty < vendorPOItemEntities[rowIndex].RequestQty)
                        {
                            vendorPOItemEntities[rowIndex].Status = "ongoing";
                        }
                        if (vendorPOItemEntities[rowIndex].CompleteQty >= vendorPOItemEntities[rowIndex].RequestQty)
                        {
                            vendorPOItemEntities[rowIndex].Status = "completed";
                        }
                        if (vendorPOItemEntities[rowIndex].CompleteQty == 0)
                        {
                            vendorPOItemEntities[rowIndex].Status = "new";
                        }

                        Session["CloseOpen"] = "Opened";

                    }
                    else
                    {
                        if (Session["CloseOpen"].ToString() == "Opened")
                        {
                            vendorPOItemEntities[rowIndex].Status = "closed";
                            Session["CloseOpen"] = "Closed";
                        }
                    }

                }
                Session["VendorPOItems"] = vendorPOItemEntities;
                VendorPOItemGridView.DataSource = vendorPOItemEntities;
                VendorPOItemGridView.DataBind();
            }
            catch (Exception ex)
            {
                Session["FlashMessage"] = "Error: " + ex.Message;
                Session["FlashMessageType"] = "error";
            }

        }
       
        

        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            try
            {
                //before click submit button, every thing haven't been changed into database.
                //after this method called, delete all the old vendor po items, and add all new vendor po items.
                //if the po have been finish partially, cannot update cannot delete anything!
                int vendPOId = Convert.ToInt32(Request.QueryString["vendorPOId"]);
                VendorPOItemController vendorPoItemController = new VendorPOItemController();
                //vendorPoItemController.DeleteVendorPOItemByVendorPOId(vendPOId);

                //Construct the new vendor po
                VendorPOController vendorPoController = new VendorPOController();
                VendorPOEntity vendorPoEntity = new VendorPOEntity();
                vendorPoEntity.Id = vendPOId;
                vendorPoEntity.No = VendorPONoTextBox.Text.Trim();
                vendorPoEntity.VendId = Convert.ToInt32(VendorDropDownList.SelectedValue);
                vendorPoEntity.Phone = PhoneTextBox.Text.Trim();
                vendorPoEntity.Reference = RefereceTextBox.Text.Trim();
                vendorPoEntity.Remark = RemarkTextBox.Text.Trim();
                vendorPoEntity.ZipCode = ZipCodeTextBox.Text.Trim();
                vendorPoEntity.Address = AddressTextBox1.Text.Trim() +","+ AddressTextBox2.Text.Trim()+","+AddressTextBox3.Text.Trim();
                vendorPoEntity.ApprovedBy = Convert.ToInt32(ApprovedByTextBox.Text.Trim());
                vendorPoEntity.CreatedBy = Convert.ToInt32(CreatedByTextBox.Text.Trim());
                vendorPoEntity.Attention = AttentionTextBox.Text.Trim();
                vendorPoEntity.Fax = FaxTextBox.Text.Trim();
                vendorPoEntity.TotalQty = Convert.ToInt32(TotalQtyTextBox.Text);
                vendorPoController.UpateVendorPO(vendorPoEntity);
                IList<VendorPOItemEntity> vendorPOItemEntities = new List<VendorPOItemEntity>();
                foreach (GridViewRow r in VendorPOItemGridView.Rows)
                {
                    VendorPOItemEntity vendorPoItemEntity=new VendorPOItemEntity();
                    vendorPoItemEntity.VendPoId = vendPOId;
                    vendorPoItemEntity.Lot = Convert.ToInt32(((TextBox)r.FindControl("LotTextBox")).Text);
                    vendorPoItemEntity.Price = Convert.ToDecimal(((TextBox)r.FindControl("PriceTextBox")).Text);
                    vendorPoItemEntity.ProductId =
                        (Session["VendorPOItems"] as IList<VendorPOItemEntity>)[r.RowIndex].ProductId;
                    vendorPoItemEntity.Remark = ((TextBox)r.FindControl("RemarkTextBox")).Text;
                    vendorPoItemEntity.RequestDate = Convert.ToDateTime(((TextBox)r.FindControl("RequestDateTextBox")).Text);
                    vendorPoItemEntity.RequestQty = Convert.ToInt32(((TextBox)r.FindControl("QtyTextBox")).Text);
                    vendorPoItemEntity.Status = (Session["VendorPOItems"] as IList<VendorPOItemEntity>)[r.RowIndex].Status;
                    vendorPoItemEntity.Id = (Session["VendorPOItems"] as IList<VendorPOItemEntity>)[r.RowIndex].Id;
                    vendorPOItemEntities.Add(vendorPoItemEntity);
                    
                }
                Session["VendorPOItems"] = vendorPOItemEntities;
                foreach (VendorPOItemEntity vendorPoItemEntity in (Session["VendorPOItems"] as IList<VendorPOItemEntity>))
                {
                    if (vendorPoItemEntity.Id == 0)
                    {
                        vendorPoItemEntity.Status = "new";
                        //vendorPoItemEntity.Remark = "";
                        //vendorPoItemEntity.VendPoId = vendPOId;
                        vendorPoItemController.AddVendorPOItem(vendorPoItemEntity);
                    }
                    else
                    {
                        vendorPoItemController.UpdateVendorPOItemByVendorPOItemId(vendorPoItemEntity);
                    }
                }
                Session["FlashMessage"] = "Success: Update Successful!";
                Session["FlashMessageType"] = "success";
            }
            catch(Exception ex)
            {
                Session["FlashMessage"] = "Error: "+ex.Message;
                Session["FlashMessageType"] = "error";
            }

        }

        protected void InsertButton_Click(object sender, EventArgs e)
        {
            IList<VendorPOItemEntity> vendorPOItemEntities = Session["VendorPOItems"] as IList<VendorPOItemEntity>;
            VendorPOItemEntity vendorPOItemEntity = new VendorPOItemEntity();
            ProductEntity productEntity = this.ConstructProductEntity();
            ProductNameLabel.Text = productEntity.Name;

            vendorPOItemEntity.ProductId = productEntity.Id;
            vendorPOItemEntity.ProductNo = productEntity.No;
            vendorPOItemEntity.ProductName = productEntity.Name;
            vendorPOItemEntity.Rev = productEntity.Revision;
            vendorPOItemEntity.RequestDate = Convert.ToDateTime(InsertRequestedDateTextBox.Text.Trim());
            vendorPOItemEntity.Price = Convert.ToDecimal(InsertPriceTextBox.Text.Trim());
            vendorPOItemEntity.Lot = Convert.ToInt32(InsertLotTextBox.Text.Trim());
            vendorPOItemEntity.RequestQty = Convert.ToInt32(InsertQtyTextBox.Text.Trim());
            vendorPOItemEntity.NoAndRev = NoAndRevDropDownList.SelectedItem.Text.Trim();
            vendorPOItemEntity.FormatDate = InsertRequestedDateTextBox.Text.Trim();
            vendorPOItemEntity.Id = 0;
            vendorPOItemEntity.Status = "new";
            vendorPOItemEntities.Add(vendorPOItemEntity);
            Session["VendorPOItems"] = vendorPOItemEntities;
            VendorPOItemGridView.DataSource = vendorPOItemEntities;
            VendorPOItemGridView.DataBind();
            
        }

        protected void NoAndRevDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (NoAndRevDropDownList.SelectedIndex != 0)
            {
                InsertButton.Enabled = true;
                ProductEntity productEntity = this.ConstructProductEntity();
                ProductNameLabel.Text = productEntity.Name;
            }
            else
            {
                InsertButton.Enabled = false;
                ProductNameLabel.Text = "";
            }
        }
        private ProductEntity ConstructProductEntity()
        {
            int productId = Convert.ToInt32(NoAndRevDropDownList.SelectedValue);
            ProductController productController = new ProductController();
            ProductEntity productEntity = productController.FindProductById(productId);
            return productEntity;
        }
    }
}
